<!DOCTYPE html>
<script src="/js-test-resources/js-test.js"></script>
<script>
description("Test that WebSockets are not subject to the HTTP connection limit.");

window.jsTestIsAsync = true;

const SOCKETS_TO_OPEN = 50;
// PARALLELISM limits the number of connections we try to open simultaneously.
// This avoids triggering the throttling added in http://crrev.com/972963002,
// which slows the test down considerably. 4 is the maximum number of
// simultaneous pending connections guaranteeed to have zero throttling delay
// applied, but parallelism of 2 seems to give the best performance in practice.
const PARALLELISM = 2;

var socketsOpened = 0;
var sockets = [];

function createNewWebSocket()
{
    var ws = new WebSocket("ws://127.0.0.1:8880/echo");
    sockets.push(ws);
    ws.onopen = function() {
        if (sockets.length < SOCKETS_TO_OPEN) {
            createNewWebSocket();
        }
        ++socketsOpened;
        if (socketsOpened == SOCKETS_TO_OPEN) {
            cleanUpSocketsAndFinish();
        }
    };
    ws.onclose = function() {
        testFailed("unexpected close event");
        cleanUpSocketsAndFinish();
    };
}

function cleanUpSocketsAndFinish()
{
    for (var ws of sockets) {
        ws.onclose = null;
        ws.close();
    }
    shouldBeEqualToNumber("socketsOpened", SOCKETS_TO_OPEN);
    finishJSTest();
}

for (var i = 0; i < PARALLELISM; ++i) {
    createNewWebSocket();
}
</script>
